package com.si.rapid;


import java.io.IOException;
import java.io.StringReader;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import net.htmlparser.jericho.Element;
import net.htmlparser.jericho.MasonTagTypes;
import net.htmlparser.jericho.MicrosoftTagTypes;
import net.htmlparser.jericho.Source;

import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import android.app.ListActivity;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.si.rapid.XML.RapidList;
import com.si.rapid.XML.SearchList;
import com.si.rapid.XML.XMLHandler;
import com.si.rapid.library.ApiFilestube.Search;
/**
 * A class controls the window of searchs and invoque all the main functions
 * @author Carlos Martinez
 *
 */
public class SearchListActivity extends ListActivity {
	
	private Search consulta;
	private Search FileToRapid;
	private String TextResponse="";
	private String TextToSearch="";
	private SearchList ListaEnlaces=null;
	private RapidList RapidEnlaces=null;
	private ArrayList<String> Names=null;
	private ArrayList<String> Links=null;
	
	//String[] Consulta = {"Consulta"};
	String[] Consulta= null;
	
    public class MyCustomAdapter extends ArrayAdapter<String> {
    	
		public MyCustomAdapter(Context context, int textViewResourceId,
				String[] objects) {
			super(context, textViewResourceId, objects);
			// TODO Auto-generated constructor stub
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			//return super.getView(position, convertView, parent);
			LayoutInflater inflater=getLayoutInflater();
			View row=inflater.inflate(R.layout.search_list_row, parent, false);
			TextView label=(TextView)row.findViewById(R.id.TextSearchRow);
			//label.setText(Integer.toString(position+1)+"\t\t");
			label.setText(Consulta[position]);
			TextView label1=(TextView)row.findViewById(R.id.TextSearchRowService);
			//label1.setText(DayOfWeek[position]);
			//label1.setText(TextResponse);
			label1.setText(Links.get(position));
			return row;
		}
	}

	
	private void Ejecutar(){
		consulta=new Search();
        consulta.execute_search(TextToSearch, null, null, 0, null);
        TextResponse=new String(consulta.getXmlText());
	}
	
	private void ProcessXML(){
		
		try {

			/** Handling XML */
			SAXParserFactory spf = SAXParserFactory.newInstance();
			SAXParser sp = spf.newSAXParser();
			XMLReader xr = sp.getXMLReader();


			/** Create handler to handle XML Tags ( extends DefaultHandler ) */
			XMLHandler myXMLHandler = new XMLHandler();
			xr.setContentHandler(myXMLHandler);
			xr.parse(new InputSource(new StringReader(TextResponse)));

		} catch (Exception e) {
			System.out.println("XML Pasing Exception = " + e);
		}

		/** Get result from MyXMLHandler SitlesList Object */
		ListaEnlaces = XMLHandler.searchList;		
	}
	
	private void GetRapidshareUrls(){
		Names=new ArrayList<String>();
		Links=new ArrayList<String>();
		URI uri = null;
		URL url = null;
		Source source=null;
		
		//Control the exceptions of the urls
		int flag_uri = 0;
		int flag_url = 0;
		int flag_source = 0;
		
		for(int i=0;i<ListaEnlaces.size();i++){
			uri = null;
			url = null;
			flag_uri=0;
			flag_url=0;
			flag_source=0;
			
			//FileToRapid=new Search();
			//FileToRapid.Consulta(ListaEnlaces.getAddress().get(i));
			Names.add(ListaEnlaces.getName().get(i));
			
			
			
			MicrosoftTagTypes.register();
			MasonTagTypes.register();
			source = null;
				
			try{
				uri=new URI(ListaEnlaces.getAddress().get(i));
			}catch (URISyntaxException e1){
				flag_uri=1;
				e1.printStackTrace();
			}
			
			if(flag_uri==0){
				try{
					url = uri.toURL();
				} catch (MalformedURLException e2) {
					// TODO Auto-generated catch block
					flag_url=1;
					e2.printStackTrace();
				}
			}
			
			
			if(flag_url==0 && flag_uri==0){
				try {
					source = new Source(url);
				} catch (MalformedURLException e) {
					// TODO Auto-generated catch block
					flag_source=1;
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					flag_source=1;
					e.printStackTrace();
				}
			}
			
			
			List<Element> elementList=null;
			if(flag_uri==0 && flag_url==0 && flag_source==0){
				try {
					elementList = source.getAllElements("pre");
					if(elementList.size()>0){
						for (Element element : elementList) {
							Links.add(element.getContent().toString());
						}
					}
					else
						Links.add(Globals.noLink);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					Links.add(Globals.noLink);
					e.printStackTrace();
				}
			}
			else{
				Links.add(Globals.noLink);
			}
			
		}
			
//			try {
//
//				/** Handling XML */
//				SAXParserFactory spf = SAXParserFactory.newInstance();
//				SAXParser sp = spf.newSAXParser();
//				XMLReader xr = sp.getXMLReader();
//
//
//				/** Create handler to handle XML Tags ( extends DefaultHandler ) */
//				XMLHandler myXMLHandler = new XMLHandler();
//				xr.setContentHandler(myXMLHandler);
//				xr.parse(new InputSource(new StringReader(FileToRapid.getUrlText())));
//
//			} catch (Exception e) {
//				System.out.println("XML Pasing Exception = " + e);
//			}
//
//			/** Get result from MyXMLHandler SitlesList Object */
//			RapidEnlaces = XMLHandler.getRapidList();
			
			
			
			//Links.add(RapidEnlaces.getAddress());
			//Links.add(FileToRapid.getUrlText());
	
	}
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	
        super.onCreate(savedInstanceState);
        TextToSearch=new String(this.getIntent().getExtras().getString("Search"));
        Ejecutar();
        ProcessXML();
        GetRapidshareUrls();
        //setContentView(R.layout.search_list);
        /*setListAdapter(new ArrayAdapter<String>(this, 
        		R.layout.row, R.id.weekofday, DayOfWeek));*/
       // setListAdapter(new MyCustomAdapter(SearchListActivity.this, R.layout.search_list_row, DayOfWeek));
        Consulta=new String[Names.size()];
        
        for(int i=0;i<Names.size();i++)
        	Consulta[i]=Names.get(i).toString();
        
        if(Consulta.length==0)
        	Toast.makeText(this, R.string.textNoSearchs, Toast.LENGTH_SHORT).show();
        	
        setListAdapter(new MyCustomAdapter(SearchListActivity.this, R.layout.search_list_row,  Consulta));
        
    }

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		// TODO Auto-generated method stub
		//super.onListItemClick(l, v, position, id);
		String selection = l.getItemAtPosition(position).toString();
		Toast.makeText(this, selection, Toast.LENGTH_LONG).show();
	}
}
